package dawn.jxufe.community.controller;

import dawn.jxufe.community.entity.Event;
import dawn.jxufe.community.event.EventProducer;
import dawn.jxufe.community.util.CommunityConstant;
import dawn.jxufe.community.util.CommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dawn21
 * @version 1.0
 * @date 2022/9/1 17:55
 * @component
 */
@Controller
public class ShareController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);

    @Autowired
    private EventProducer eventProducer;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String context;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    // https://community-share-lxliujx.oss-cn-hangzhou.aliyuncs.com
    @Value("${aliyun.bucket.community.share.url}")
    private String shareBucketUrl;

    // 生成后共享。
    @RequestMapping(path = "/share", method = {RequestMethod.POST, RequestMethod.GET})
    //@ResponseBody
    public String share(String htmlUrl, Model model) {
        // 随机照片文件名字。
        String fileName = CommunityUtil.generateUUID();
        // 异步生成 长图
        Event event = new Event()
                .setTopic(TOPIC_SHARE)
                .setData("htmlUrl", htmlUrl) // 截屏网站地址
                .setData("fileName", fileName) // 文件名
                .setData("suffix", ".png"); // 文件后缀
        eventProducer.fireEvent(event);
        // 返回访问路径
        //Map<String, Object> map = new HashMap<>();
        //map.put("shareUrl", domain + context + "/share/image/" + fileName);
        model.addAttribute("htmlUrl", htmlUrl);
        model.addAttribute("fileName", fileName);
        model.addAttribute("shareUrl", shareBucketUrl + "/" + fileName + ".png");

        //return CommunityUtil.getJSONString(0, null, map);
        return "forward:/data";
    }

    // 获取长图
    @RequestMapping(path = "/share/image/{fileName}", method = RequestMethod.GET)
    public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        if (StringUtils.isBlank(fileName)) {
            throw new IllegalArgumentException("文件名不能为空！");
        }

        // 原来的fileName：xxx.png
        // 服务器上路径。全限定名。带上了本地路径。
        fileName = shareBucketUrl + "/" + fileName;
        // 声明输出的文件的格式(文件的后缀)。
        // 文件的后缀。不要点。
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

        response.setContentType("image/" + suffix);
        //File file = new File(wkImageStorage + "/" + fileName + ".png");
        try {
            FileInputStream fileInputStream = new FileInputStream(fileName);
            OutputStream os = response.getOutputStream();
            //FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fileInputStream.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("获取长图失败：" + e.getMessage());
        }
    }

}
